/**
 * 知识库管理
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    var dialog = require("dialogplus");
    var util = require("util");
    var ui = require("ui");
    var tmpl = require("tmpl");
    require("jqtree");
    require("pagination");
    require("permission");
    require('authorize');
    var api_prefix = G_CONFIG["api_prefix"] + "/qmyx/knowledge/"; //api前缀

    var KnowLedgeMng = {
        token: null,
        typeTotal: 0,
        typeList: [],
        knowledgeTotal: 0,
        knowledgeList: [],
        selTypeId: null, //选择的类型id
        pageIndex:1,
        pageSize:10,
        pagerInited:false,
        init: function() {
            this.token = util.getToken();
            this.bindEvent();
            this.getTypeList();
            this.initTypeTree();
        },
        bindEvent: function() {
            var _this = this;
            $("#btn_add_type").on("click", function(e) {
                e.preventDefault();
                _this.showAddType();
            });
            $("#btn_add").on("click", function(e) {
                e.preventDefault();
                _this.showAddKnowledge("",{});
            });
            $("#knowledge_tbl").on("click", ".icon-op-edit", function(e) {
                e.preventDefault();
                var oid = $(e.currentTarget).closest("td").attr("id") || "";
                if (oid) {
                    _this.showUpdateKnowledge(oid);
                }
            });
            $("#knowledge_tbl").on("click", ".icon-op-del", function(e) {
                e.preventDefault();
                var oid = $(e.currentTarget).closest("td").attr("id") || "";
                if (oid) {
                    _this.delKnowledge(oid);
                }
            });
            $("#knowledge_tbl").on("mouseenter","tr",function(){
                $(this).find(".js-oper-btn").show();
            });
            $("#knowledge_tbl").on("mouseleave","tr",function(){
                $(this).find(".js-oper-btn").hide();
            });
        },
        showUpdateKnowledge: function(oid) {
            var knowledge;
            $.each(this.knowledgeList, function(i, item) {
                if (item.b_knowledgeId == oid) {
                    knowledge = item;
                    return false;
                }
            });
            if (!knowledge) {
                ui.showErrTip("未找到知识对象");
                return;
            }
            this.showAddKnowledge(knowledge.b_knowledgeId, knowledge);
        },
        /**
         * 校验是否选择了知识库类型
         * @returns {Boolean}
         */
        checkSelType: function() {
            var node = $("#type_tree").tree('getSelectedNode');
            if (!node) {
                var tip = this.typeTotal > 0 ? "请先选择知识库类别" : "请先添加知识库类别";
                util.alert(tip);
                return false;
            }
            return node;
        },
        showAddType: function(oid, type_name) {
            var title = oid ? "编辑类别" : "新增类别";
            var html = tmpl("addtype_tmpl", {type_name: type_name});
            var _this = this;
            var d = dialog({
                title: title,
                id:"add_type_dialog",
                width:400,
                height:65,
                fixed: true,
                content: html,
                ok: function() {
                    var $type_name = $("#txt_type_name");
                    var type_name = $.trim($type_name.val());
                    if (!type_name) {
                        $type_name.nextAll(".js-err").html("请填写类别名称");
                        return false;
                    } else {
                        $type_name.nextAll(".js-err").html("");
                    }
                    _this.saveType(oid, type_name);
                    return false;
                },
                cancel: function() {
                }
            }).showModal();
        },
        //新增,编辑知识弹层
        showAddKnowledge: function(oid, knowledge) {
            var selType = this.checkSelType();
            if (!selType) {
                return;
            }
            var title = oid ? "编辑记录" : "新增记录";
            var data = {
                type_name: selType.name,
                title: knowledge.title,
                intro: knowledge.intro,
                content: knowledge.content,
                show_pic: knowledge.show_pic,
                keywords: knowledge.keywords,
                cover_pic_url: knowledge.cover_pic_url
            };
            var html = tmpl("add_knowledge_tmpl", data);
            var _this = this;
            var d = dialog({
                title: title,
                id:"add_knowledge_dialog",
                content: html,
                width:850,
                height:550,
                onshow: function() {
                    ui.initSwitch("#rbt_show_pic");
                    require.async(["uploader"], function() {
                        $('#fileupload').fileupload({
                            dataType: 'json',
                            url: G_CONFIG["api_prefix"] + "common/file/upload-image",
                            add:function(e,data){
                                if(util.checkIsImagFile(data.files[0])){
                                    data.submit();
                                    $("#img_wrap").append('<div class="upload-process">上传中...</div>');
                                }else{
                                    $("#fileupload").nextAll(".js-err").html("请选择图片文件(jpg|jpeg|png)").show();
                                }
                            },
                            done: function(e, data) {
                                $("#img_wrap").find(".upload-process").remove();
                                var res = data.result;
                                if (res.retCode == "0") {
                                    var img_url = res.data.path;
                                    $("#img_wrap").html('<img src="' + img_url + '" />');
                                    $("#cover_pic_url").val(img_url);
                                    $("#fileupload").nextAll(".js-err").html("");
                                } else {
                                    $("#fileupload").nextAll(".js-err").html("上传失败:" + res.errMsg).show();
                                }
                            }
                        });
                    });
                    //初始化编辑器
                    var editor = new UE.ui.Editor({
                        zIndex: 9999,
                        toolbars:window.UEDITOR_CONFIG.toolbarStyles["default"]
                    });
                    editor.ready(function(){
                        if(data.content){
                            editor.setContent(data.content);
                        }
                    });
                    editor.render("editor");
                },
                onclose:function(){
                },
                ok: function() {
                    var title = ui.checkField("txt_title", true);
                    var keywords = ui.checkField("txt_keywords");
                    var intro = ui.checkField("txt_intro");
                    var cover_pic_url = ui.checkField("cover_pic_url", true);
                    var show_pic = $("#rbt_show_pic").hasClass("switch-on") ? "1" : "0";
                    var content = ui.checkEditor("editor",true);
                    if (title === false || keywords === false || intro === false 
                        || cover_pic_url === false || content === false) {
                        return false;
                    }
                    _this.saveKnowledge(oid,selType,title, keywords, intro, content, cover_pic_url, show_pic);
                    return false;
                },
                cancel: function() {                
                }
            });
            d.showModal();
        },
        /**
         * 新增、更新知识
         * @param {type} oid 主键b_knowledgeId
         * @param {type} knowledge_type 知识库类型对象
         * @param {type} title 标题
         * @param {type} keywords 关键字
         * @param {type} intro 介绍
         * @param {type} content 内容
         * @param {type} cover_pic_url 封面图片
         * @param {type} show_pic 是否显示图片
         * @returns {undefined}
         */
        saveKnowledge: function(oid,knowledge_type,title, keywords, intro, content, cover_pic_url, show_pic) {
            if(this.isSubmit){
                ui.showErrTip("请勿重复提交");
                return;
            }
            var url = oid ? "update-knowledge" : "create-knowledge";
            var data = {
                token: this.token
            };
            var knowledge = {
                title: title,
                keywords: keywords,
                intro: intro,
                content: content,
                cover_pic_url: cover_pic_url,
                show_pic: show_pic
            };
            if(oid){ //更新
                knowledge.b_knowledge_id = oid;
            }else{//新增
                data.oid = knowledge_type.id; //知识库类型id
            }
            data.knowledge = JSON.stringify(knowledge);
            util.myAjax({
                url: api_prefix + url,
                type: "POST",
                context: this,
                data: data,
                success: function(json) {
                    this.isSubmit = false;
                    if (json.retCode == 0) {
                        dialog.get("add_knowledge_dialog").remove();
                        ui.showSucTip("操作成功");
                        this.pagerInited = false;
                        this.getKnowledgeList(this.selTypeId);
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                },
                complete:function(){
                    this.isSubmit = false;
                }
            });
            this.isSubmit = true;
        },
        //保存类型
        saveType: function(oid, type_name) {
            var url = oid ? "update-knowledge-type" : "create-knowledge-type";
            var data = {
                token: this.token,
                type_name: type_name
            };
            if (oid) {
                data.oid = oid;
            }
            util.myAjax({
                url: api_prefix + url,
                type: "POST",
                context: this,
                data: data,
                success: function(json) {
                    if (json.retCode == 0){
                        dialog.get("add_type_dialog").remove();
                        this.getTypeList();
                    } else {
                        $("#txt_type_name").nextAll(".js-err").html(json.errMsg);
                        //ui.showErrTip(json.errMsg);
                    }
                }
            });
        },
        //删除类型
        delType: function(oid) {
            var _this = this;
            util.confirm("您确定要删除吗？", {
                ok: function() {
                    var url = api_prefix + "delete-knowledge-type";
                    var data = {
                        token: _this.token,
                        oid: oid
                    };
                    util.myAjax({
                        url: url,
                        type: "POST",
                        data: data,
                        success: function(json) {
                            if (json.retCode == 0) {
                                _this.getTypeList();
                            } else {
                                ui.showErrTip(json.errMsg);
                            }
                        }
                    });
                }
            });
        },
        delKnowledge: function(oid) {
            var _this = this;
            util.confirm("您确定要删除吗？", {
                ok: function() {
                    var url = api_prefix + "delete-knowledge";
                    var data = {
                        token: _this.token,
                        oid: oid
                    };
                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: _this,
                        data: data,
                        success: function(json) {
                            if (json.retCode == 0){
                                _this.pagerInited = false;
                                _this.getKnowledgeList(_this.selTypeId);
                            } else {
                                ui.showErrTip(json.errMsg);
                            }
                        }
                    });
                }
            });
        },
        getTypeList: function() {
            var url = api_prefix + "get-knowledge-type-list";
            util.myAjax({
                url: url,
                type: "GET",
                cache: false,
                data: {
                    token: this.token
                },
                context: this,
                success: function(json) {
                    if (json.retCode == 0) {
                        this.typeList = json.data || []; // 知识类别列表
                        this.typeTotal = this.typeList.length;

                        $.each(this.typeList, function(i, item) {
                            item.id = item.b_knowledge_typeId;
                            delete item.b_knowledge_typeId;
                            item.name = item.type_name;
                            delete item.type_name;
                        });
                        var $tree = $('#type_tree');
                        $tree.tree('loadData', this.typeList);
                        if (this.typeList.length > 0) {
                            //选中第一条记录
                            var firstNode = $tree.tree('getNodeById', this.typeList[0].id);
                            if(this.selTypeId){
                                var node = $tree.tree('getNodeById', this.selTypeId);
                                if(node != null){
                                    $tree.tree('selectNode', node);
                                }else{
                                    $tree.tree('selectNode', firstNode);
                                }
                            }else{
                                $tree.tree('selectNode', firstNode);
                            }
                        }
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                }
            });
        },
        //查询知识列表
        getKnowledgeList: function(oid,pageIndex) {
            var _this = this;
            if (!oid) {
                return;
            }
            if(typeof pageIndex == "undefined"){
                pageIndex = 1;
            }
            var url = api_prefix + "get-knowledge-list";
            util.myAjax({
                url: url,
                type: "GET",
                cache: false,
                data: {
                    token: this.token,
                    oid: oid, //类型id
                    page_index: pageIndex,
                    page_size:this.pageSize
                },
                context: this,
                success: function(json) {
                    if (json.retCode == 0) {
                        this.knowledgeTotal = json.data.knowledge_total;
                        this.knowledgeList = json.data.knowledge_list || []; // 知识列表

                        this.initKnowledgeTable(this.knowledgeList);
                        if(!this.pagerInited){
                            this.initPager(this.knowledgeTotal);
                        }
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                },
                complete:function(){
                    ui.removeLoading();
                    _this.checkHeight();
                }
            });
            ui.loading("grid");
        },
        initPager:function(total){
            var _this = this;
            $('#pager').pagination(total,{
                num_edge_entries: 1, //边缘页数
                num_display_entries: 4, //主体页数
                callback: function (pageIndex, jq) {
                    _this.pageIndex = pageIndex;
                    _this.getKnowledgeList(_this.selTypeId,pageIndex);
                },
                items_per_page: this.pageSize //每页显示1项
            });
            this.pagerInited = true;
        },
        appendBtn: function(node) {
            var actionCls = "permission p-500309-11-inline-block";
            var str = '<span class="fr left-list-op">';
            str += this.getBtnHtml("编辑","icon-op-edit",actionCls);
            str += this.getBtnHtml("删除","icon-op-del",actionCls);
            //上移下移按钮
            var isFirstNode = node.getPreviousSibling() == null; //同级第一个节点
            var isLastNode = node.getNextSibling() == null; //同级最后一个节点
            if (!isLastNode) { //下移权限
                str += this.getBtnHtml("下移","icon-op-down",actionCls);
            }
            if (!isFirstNode) { //上移权限
                str += this.getBtnHtml("上移","icon-op-up",actionCls);
            }
            return str + "</span>";
        },
        getBtnHtml:function(title,iconCls,actionCls){
            return '<a href="javascript:void(0)" title="' + title + '" class="' + actionCls + '"><i class="icon-op ' + iconCls + '">&nbsp;</i></a>';
        },
        initTypeTree: function() {
            var $tree = $("#type_tree");
            var _this = this;
            $tree.tree({
                data: [],
                dragAndDrop: true,
                useContextMenu: false,
                //创建节点时
                onCreateLi: function(node, $li) {
                    var btn_str = _this.appendBtn(node);
                    $li.find(".jqtree-element").append(btn_str);
                },
                //是否可以移动
                onCanMove: function(node) {
                    return true;
                },
                //是否可以移动到
                onCanMoveTo: function(moved_node, target_node, position) {
                    //只能在同级节点中移动
                    if (position == "before" || position == "after") {
                        $("#type_tree .jqtree-dragging > i").removeClass("icon-op-stop");
                        return true;
                    } else {
                        $("#type_tree .jqtree-dragging > i").addClass("icon-op-stop");
                        return false;
                    }
                },
                //移动句柄
                onIsMoveHandle: function($ele) {
                    if ($ele.hasClass('jqtree-title')) {
                        $ele.css("cursor", "move");
                        return true;
                    }
                    return false;
                }
            });
            //绑定操作事件
            $tree.bind('tree.click', function(e) {
                var node = e.node;
                if (e.click_event) {
                    var $el = $(e.click_event.target);
                    if ($el.hasClass("icon-op-edit")) {
                        _this.showAddType(node.id, node.name);
                    } else if ($el.hasClass("icon-op-del")) {
                        _this.delType(node.id);
                    } else if ($el.hasClass("icon-op-down")) {
                        _this.moveNode(node, node.getNextSibling(), "after");
                    } else if ($el.hasClass("icon-op-up")) {
                        _this.moveNode(node, node.getPreviousSibling(), "before");
                    }
                }
            });
            //移动节点前触发
            $tree.bind('tree.move', function(e) {
                e.preventDefault(); //阻止移动
                if (e.move_info) {
                    _this.moveNode(e.move_info.moved_node, e.move_info.target_node, e.move_info.position);
                }
            });
            $tree.bind('tree.select', function(event) {
                if (event.node) {
                    var node = event.node;
                    _this.selTypeId = node.id;
                    _this.pagerInited = false;
                    _this.getKnowledgeList(node.id);
                }
            });
            // $tree.on("mouseenter","li",function(){
            //     $(this).find(".left-list-op").show();
            // });
            // $tree.on("mouseleave","li",function(){
            //     $(this).find(".left-list-op").hide();
            // });
        },
        moveNode: function(node, target_node, position) {
            if (!target_node) {
                ui.showErrTip("节点未找到");
                return;
            }
            //移动节点
            $("#type_tree").tree('moveNode', node, target_node, position);
            //保存数据
            var parentNode = node.parent; //获取父节点
            var data = parentNode.getData();//将父节点下所有数据序列化为json传到后台
            var types = [];
            $.each(data, function(i, type) {
                types.push({oid: type.id, sort: type.sort});
            });
            var url = api_prefix + "order-knowledge-types";
            var data = {
                token: this.token,
                knowledge_types: JSON.stringify(types)
            };
            util.myAjax({
                url: url,
                type: "POST",
                context: this,
                data: data,
                success: function(json) {
                    if (json.retCode != 0) {
                        $("#type_tree").tree('moveNode', target_node, node, position); //还原位置
                        ui.showErrTip(json.errMsg);
                    }
                }
            });
        },
        initKnowledgeTable: function(list) {
            if(list.length > 0){
                var html = tmpl('tbl_row_tmpl', {list: list});
                $("#knowledge_tbl").html(html);
            }else{
                $("#knowledge_tbl").html('<tr><td colspan="4"><div class="no-data"><span>暂无数据</span></div></td></tr>');
            }
        },
        checkHeight: function(){
            var con_height = $("#leftListCon").height();
            if(con_height > 428){
                $("#leftList").css("min-height",con_height+22);
            }
        }
    };
    module.exports = KnowLedgeMng;
});